package com.example.prompt.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.prompt.dto.PromptRequest;
import com.example.prompt.dto.PromptResponse;
import com.example.prompt.service.PromptService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Validated
@RestController
@RequestMapping("/api/prompt")
@RequiredArgsConstructor
public class PromptController {
    private final PromptService promptService;
    private final ObjectMapper objectMapper;

    @PostMapping("/optimize")
    public ResponseEntity<PromptResponse> optimizePrompt(@Valid @RequestBody PromptRequest request) throws JsonProcessingException {
        try {
            log.info("Received request: {}", objectMapper.writeValueAsString(request));
            String optimizedPrompt = promptService.optimizePrompt(request);
            PromptResponse response = PromptResponse.of(optimizedPrompt);
            log.info("Sending response: {}", objectMapper.writeValueAsString(response));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error processing request", e);
            throw e; // 直接抛出原始异常
        }
    }

    @GetMapping("/test")
    public String test() {
        return "API is working!";
    }
}